package com.jiemengshi.server.controller;

import com.jiemengshi.server.model.Feedback;
import com.jiemengshi.server.service.WechatFeedbackService;
import com.jiemengshi.server.service.WechatUserService;
import com.jiemengshi.server.util.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;

@Controller
@RequestMapping(value = {"/{appName}/wechat/feedback"}, produces = {"application/json;charset=UTF-8"})
public class WechatFeedbackController {
    private Logger log = LoggerFactory.getLogger(this.getClass());
    
    @Autowired
    private WechatFeedbackService feedbackService;

    @Autowired
    private WechatUserService userService;
    
    @ResponseBody
    @RequestMapping("/add")
    public String addFeedback(HttpServletRequest request, Feedback feedback){
        try {
            if(StringUtil.isEmpty(feedback.getContent()))
                throw new PrjException(ErrorCodeMsg.FEEDBACK_CONTENT_EMPTY);

            feedback.setUserId(userService.getLoginUserId(request));
            if(feedbackService.addFeedback(feedback))
                return ApiResult.SUCCESS;
            else
                throw new PrjException(ErrorCodeMsg.FEEDBACK_ADD_ERROR); 
        } catch (PrjException e){
            return ApiResult.writeException(e);
        } catch (Exception e) {
            log.error(ApiJson.toJson(request.getParameterMap()));
            log.error(PrjException.getTrace(e));
            return ApiResult.SYSTEM_ERROR;
        }
    }

    @ResponseBody
    @RequestMapping("/list")
    public String listFeedback(HttpServletRequest request){
        try {
            return ApiResult.writeData(feedbackService.getFeedbackByUserId(userService.getLoginUserId(request)));
        } catch (PrjException e){
            return ApiResult.writeException(e);
        } catch (Exception e) {
            log.error(ApiJson.toJson(request.getParameterMap()));
            log.error(PrjException.getTrace(e));
            return ApiResult.SYSTEM_ERROR;
        }
    }
}
